#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void dfs(TreeNode* root, vector<int>& s) {
        if (!root)return;
        s.push_back(root->val);
        dfs(root->left, s);
        dfs(root->right, s);
    }
    int Binary1(vector<int>& s, int x) {
        int l = -1;
        int r = s.size();
        while (l + 1 != r) {
            int mid = (l + r) >> 1;
            if (s[mid] <= x)l = mid;
            else r = mid;
        }
        if (l < 0 || l >= s.size())return -1;
        return s[l];
    }
    int Binary2(vector<int>& s, int x) {
        int l = -1;
        int r = s.size();
        while (l + 1 != r) {
            int mid = (l + r) >> 1;
            if (s[mid] >= x)r = mid;
            else l = mid;
        }
        if (r < 0 || r >= s.size())return -1;
        return s[r];
    }
    vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) {
        vector<int> s;
        int n = queries.size();
        dfs(root, s);
        sort(s.begin(), s.end());
        //for(auto it:s)cout<<it<<endl;
        vector<vector<int>>ans;
        for (int i = 0; i < n; i++) {
            int a = Binary1(s, queries[i]);
            // cout<<a<<endl;
            int b = Binary2(s, queries[i]);
            ans.push_back({ a,b });
        }
        return ans;
    }
};